﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
using System.Diagnostics;
using System.Collections;

namespace Autofac {
    public class BankInterceptor : IInterceptor {

        public void Intercept(IInvocation invocation) {

            var returnType = invocation.Method.ReturnType;

            if (returnType.Name.Equals("Void")) {
                return;
            }

            if (returnType.GetInterfaces().Any(i => i.Name.Contains("IList"))) {
                invocation.ReturnValue = GenerateList(returnType);
                return;
            }

            if (returnType.BaseType.Name.Equals("DbObject")) {
                invocation.ReturnValue = CreateInstance(returnType, 1);
                return;
            }

            if (returnType.Name.Equals("String")) {
                invocation.ReturnValue = returnType.Name;
                return;
            }

            if (returnType.Name.Equals("Decimal")) {

                invocation.ReturnValue = 58.9968;
                return;
            }

            if (returnType.Name.Equals("Int32")) {
                invocation.ReturnValue = 125;
                return;
            }
        }

        private IList GenerateList(Type type) {
            var item = Activator.CreateInstance(type);

            Debug.Assert(type.GetGenericArguments().Length > 0);
            var entityType = type.GetGenericArguments()[0];
            var list = (IList)Activator.CreateInstance(type);
            for (var i = 0; i < 10; i++) {

                list.Add(CreateInstance(entityType, i));

            }
            return list;
        }


        private Func<Type, int, object> CreateInstance = (type, i) =>
        {
            var entity = Activator.CreateInstance(type);
            var properties = type.GetProperties();
            foreach (var p in properties) {
                object value = null;
                if (p.PropertyType == typeof(string)) {
                    value = p.Name + i.ToString();
                    p.SetValue(entity, value, null);
                    continue;
                }
                if (p.PropertyType.IsValueType) {
                    value = 0;
                    p.SetValue(entity, value, null);
                    continue;
                }
            }
            return entity;
        };
    }
}
